package com.fingard.dsp.bank.directbank.qdcb01;


import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.ISinglePay;
import com.fingard.dsp.bank.reqrespobj.single.*;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.net.ConnState;
import com.fingard.text.StringHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

public class QDCB01SinglePay extends QDCB01Base implements ISinglePay {

    //单笔支付，不需采用流处理方式
    public RetAtsSingle d_1908_SglPay(ReqSingle p_req1908) throws Exception {
        //返回ATS的对象
        RetAtsSingle retAts = new RetAtsSingle(p_req1908.reqHeader);
        RetAtsSglDetail tmpRetDetail;
        tmpRetDetail = d_190802(p_req1908);
        if (tmpRetDetail.respCode.equals("-1") && StringHelper.isNullOrEmpty(tmpRetDetail.reqSeqID)) {
            tmpRetDetail.reqSeqID = p_req1908.singleDetail.askNumber;
        }
        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }

    @Override
    public RetAtsSingleBat d_1908BAT_SglBatPay(ReqSingleBat p_req1908BAT) throws Exception {
        return null;
    }

    //190802对外支付
    private RetAtsSglDetail d_190802(ReqSingle p_req1908) throws Exception {
        RetAtsSglDetail retDetail = new RetAtsSglDetail();
        if (p_req1908.singleDetail.sameBnk.equals("1")) {//同行
            bsnCode = "CBE003";
        } else {//跨行
            bsnCode = "CBE004";
        }
        String orderId = p_req1908.reqHeader.reqSeqID;
        serialNo = String.valueOf(Integer.parseInt(orderId, 36));//不允许含有英文字母
        //发送银行之前报文主体部分送到前置机的签名端口
        StringBuffer sb = new StringBuffer();
        String rmtType = "";//0：普通(行外小额)1：加急(行外大额)2：实时(网银互联实时支付)
        if (p_req1908.singleDetail.isLargeAmt()) {
            rmtType = "1";
        } else if (p_req1908.singleDetail.paySpd.equals("1")) {//加急走大额
            rmtType = "1";
        } else {
            rmtType = "0";
        }
        String signDataField = "";
        if ("CBE003".equals(bsnCode)) {
            signDataField = p_req1908.singleDetail.payAct + "|" + p_req1908.singleDetail.payName + "|" + p_req1908.singleDetail.recAct + "|" + p_req1908.singleDetail.recName + "|" + p_req1908.singleDetail.payAmount + "|" + convertCurToBank(p_req1908.singleDetail.payCur) + "|" + p_req1908.singleDetail.purpose;
        } else if ("CBE004".equals(bsnCode)) {
            signDataField = p_req1908.singleDetail.payAct + "|" + p_req1908.singleDetail.payName + "|" + p_req1908.singleDetail.recAct + "|" + p_req1908.singleDetail.recName + "|" + p_req1908.singleDetail.payAmount + "|" + convertCurToBank(p_req1908.singleDetail.payCur) + "|" + p_req1908.singleDetail.purpose + "|" + p_req1908.singleDetail.cnapsCode;
        }
        sb.append(signDataField);
        String signData = sb.toString();
        String[] tmpSign = sendToBankFrontSign(signData);
        if (tmpSign[0].length() == 0) {
            String signature = "";
            String body = "";
            String aa = "<result>";
            int i = tmpSign[1].indexOf(aa);
            if (i != -1) {
                body = tmpSign[1].substring(i + 8, i + 9);
            }
            if (body.equals("0")) {
                String ab = "<sign>";
                String ac = "</sign>";
                int ib = tmpSign[1].indexOf(ab);
                int ic = tmpSign[1].indexOf(ac);
                //以下为最终的签名结果
                signature = tmpSign[1].substring(ib + 6, ic).replace("\r", "").replace("\n", "");
            } else {
                retDetail.respCode = "-1";
                retDetail.respInfo = tmpSign[1];
                return retDetail;
            }
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            //写入报文头部信息
            writeCommonHeader(xmlWriter);
            XElement tmpXElement = new XElement("ReqParam", "");
            tmpXElement.addChild(new XElement("payAccount", p_req1908.singleDetail.payAct));
            tmpXElement.addChild(new XElement("payAccountName", p_req1908.singleDetail.payName));
            tmpXElement.addChild(new XElement("recAccount", p_req1908.singleDetail.recAct));
            tmpXElement.addChild(new XElement("recAccountName", p_req1908.singleDetail.recName));
            tmpXElement.addChild(new XElement("payAmount", p_req1908.singleDetail.payAmount));
            tmpXElement.addChild(new XElement("currencyType", convertCurToBank(p_req1908.singleDetail.payCur)));
            tmpXElement.addChild(new XElement("payUse", p_req1908.singleDetail.purpose));
            if ("CBE004".equals(bsnCode)) {
                tmpXElement.addChild(new XElement("unionBankNo", p_req1908.singleDetail.cnapsCode));//普通大小额转账，上送大小额联行号；如是网银互联实时转账，则为所属银行系统行号 默认使用大小额
                tmpXElement.addChild(new XElement("clearingBankNo", ""));//网银互联必输 大小额转账不需要
                tmpXElement.addChild(new XElement("rmtType", rmtType));//0：普通(行外小额)1：加急(行外大额)2：实时(网银互联实时支付)
            }
            tmpXElement.addChild(new XElement("signData", signature));
            tmpXElement.addChild(new XElement("signDataField", signDataField));
            tmpXElement.addChild(new XElement("ReqReserved1", ""));
            tmpXElement.addChild(new XElement("ReqReserved2", ""));
            nodeAnalysis(p_req1908.singleDetail.srcXElement, tmpXElement, getCharset());
            xmlWriter.writeXElement(tmpXElement);
            xmlWriter.writeEndDocument();//写入报文完成

            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());//发送银行
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                //解析银行返回
                XmlTextReader tmpBkReader = null;
                String errorCode = tmpStrRet[1].substring(0, tmpStrRet[1].indexOf("|", 0));
                String errorMsg = tmpStrRet[1].substring(tmpStrRet[1].indexOf("|", 0) + 1, tmpStrRet[1].lastIndexOf("|"));
                if (isActiveRetCode(errorCode)) {
                    tmpBkReader = loadBankRespXmlReader(tmpStrRet[1].substring(tmpStrRet[1].indexOf("<")), tmpSbMsg);
                    if (tmpBkReader != null) {
                        String orderState = "";
                        retDetail.respCode = "0";
                        retDetail.respInfo = errorMsg;
                        retDetail.reqSeqID = p_req1908.singleDetail.askNumber;
                        if ("CBE003".equals(bsnCode)) {
                            orderState = tmpBkReader.getFirstText("/QDBankData/opRep/opResult/orderState");
                        } else if ("CBE004".equals(bsnCode)) {
                            orderState = tmpBkReader.getFirstText("/resp/opRep/opResult/orderState");
                        }
                        retDetail.transState = errorCode + "+" + orderState;//90：交易成功；91：交易失败；99：交易可疑
                        retDetail.payInfoCode = retDetail.transState;
                    } else {
                        retDetail.respCode = "-1";
                        retDetail.respInfo = tmpSbMsg.toString();
                    }
                } else {
                    retDetail.respCode = "-1";
                    retDetail.respInfo = errorMsg;
                }
            } else if (tmpStrRet[0].equals(ConnState.FAIL)) {
                retDetail.respCode = "0";
                retDetail.respInfo = tmpStrRet[1];
                retDetail.reqSeqID = p_req1908.singleDetail.askNumber;
                retDetail.transState = PaymentState.FAIL_Payment;
                retDetail.payInfoCode = tmpStrRet[0];
            } else {
                retDetail.respCode = "-1";
                retDetail.respInfo = tmpStrRet[1];
            }
        } else {
            retDetail.respCode = "-1";
            retDetail.respInfo = tmpSign[1];
        }
        return retDetail;
    }

    //1944 状态查询
    public RetAtsSingle d_1944_QrySglPay(ReqQrySingle p_req1944) throws Exception {
        //返回ATS的对象
        RetAtsSingle retAts = new RetAtsSingle(p_req1944.reqHeader);
        RetAtsSglDetail retDetail = new RetAtsSglDetail();
        bsnCode = "CBE005";
        String orderId = p_req1944.reqHeader.reqSeqID;
        serialNo = String.valueOf(Integer.parseInt(orderId, 36));//不允许含有英文字母
        try {
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            writeCommonHeader(xmlWriter);//写入通用的头部节点
            xmlWriter.writeStartElement("ReqParam");
            xmlWriter.writeElementString("orderFlowNo", serialNo);
            xmlWriter.writeElementString("ReqReserved1", "");
            xmlWriter.writeElementString("ReqReserved2", "");
            xmlWriter.writeEndElement();
            xmlWriter.writeEndDocument();
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = null;
                String errorCode = tmpStrRet[1].substring(0, tmpStrRet[1].indexOf("|", 0));
                String errorMsg = tmpStrRet[1].substring(tmpStrRet[1].indexOf("|", 0) + 1, tmpStrRet[1].lastIndexOf("|"));
                if (errorCode != null && isActiveRetCode(errorCode)) {
                    tmpBkReader = loadBankRespXmlReader(tmpStrRet[1].substring(tmpStrRet[1].indexOf("<")), tmpSbMsg);
                    if (tmpBkReader != null) {
                        String tStatus = tmpBkReader.getFirstText("/QDBankData/opRep/opResult/orderState");//90：交易成功91：交易失败99：交易处理中
                        String responseResult = tmpBkReader.getFirstText("/QDBankData/opRep/opResult/responseResult");
                        retDetail.reqSeqID = p_req1944.askNumber;
                        retDetail.respCode = "0";
                        retDetail.respInfo = responseResult;
                        retDetail.payInfoCode = errorCode + "+" + tStatus;
                        retDetail.transState = errorCode + "+" + tStatus;
                    } else {
                        retDetail.respCode = "-1";
                        retDetail.respInfo = tmpSbMsg.toString();
                    }
                } else {
                    retDetail.respCode = "-1";
                    retDetail.respInfo = errorMsg;
                }
            } else {
                retDetail.respCode = "-1";
                retDetail.respInfo = tmpStrRet[1];
            }
        } catch (Exception e) {
            retDetail.respCode = "-1";
            retDetail.respInfo = e.getMessage();
            e.printStackTrace();
        }
        retAts.writeRetDetail(retDetail);
        return retAts;
    }

    @Override
    public RetAtsSingleBat d_1944BAT_QrySglBatPay(ReqQrySingleBat p_req1944BAT) throws Exception {
        return null;
    }
}
